#!/bin/bash

tar_depend () {
	mkdir -p ./tmp_depend
	# use matlab function to get dependencies
	if [ -f run.m ];then
		exit 1
	else
		cat > run.m <<EOF
my_getdependencies("${1%.m}")
EOF
	fi

	File=`matlab -batch "run"|grep No|grep -v matlab-scripts|awk '{print $2}'|sed -e "s/\r$//g"`

	rm -f run.m

	# move dependencies to tmp directory
	for file in $File
	do
	  cp $(wslpath -u $file) ./tmp_depend
	done
	# tar
	tar_name="${1%.m}-dep.tar.gz" 
	cd ./tmp_depend/ && tar -zvcf "$tar_name" ./*  && mv $tar_name $2 
	cd .. && rm -rfv ./tmp_depend
}

cp_depend () {
	if [ -f run.m ];then
		exit 1
	else
		cat > run.m <<EOF
my_getdependencies("${1%.m}")
EOF
	fi

	File=`matlab -batch "run"|grep No|grep -v matlab-scripts|awk '{print $2}'|sed -e "s/\r$//g"`
	for file in $File
	do
		if [ $(uname -a |grep -i -c wsl) -gt 0 ];then
			cp -v "$(wslpath -u $file)" "$2"
		else
			cp -v "$file" "$2"
		fi
	done

	rm -f ./run.m

}

show_help () {
	echo ""
	echo "my-matlab.sh [-h|tar|batch|back] [file]"
	echo "-----------------------------"
	echo "	my-matlab.sh tar <code.m> <dest>"
	echo "		tar dependencies of code, save into Directory <dest>"
	echo " 	my-matlab.sh cp <code.m> <dest>"
	echo "		cp dependencies of code, save into Directory <dest>"
	echo " 	my-matlab.sh back <code.m>"
	echo "		run matlab scripts in the background, without figure pop out"
	echo ""

}

case "$1" in
	tar )
		if [ -z $3 ];then
			DEST=".."
		else
			DEST="$3"
		fi
		tar_depend $2 $DEST ;;
	cp )
		if [ -z $3 ];then
			echo "my-matlab.sh cp <code.m> <dest>"
			echo "Destination needed!"
			exit 1
		fi
		cp_depend $2 $3 ;;
	batch )
		if [ -z $2 ];then
			echo "path to code!"
		else
			CodeName=${2##*/}
			matlab -batch ${CodeName%.m}
		fi
		;;
	back )
		if [ -z $2 ];then
			echo "path to code!"
		else
			CodeName=${2##*/}
			matlab -nosplash -noFigureWindows -batch ${CodeName%.m} 
		fi
		;;
	* )
		show_help;;
esac
